<template>
  <!--显示场地详细信息  场地编号 场地类型 场地图片 状态 基础价格 折扣 实际价格 场地描述 操作-->
  <div class="app-container">

    <!--    搜索框-->
    <!--    场地类型 场地状态 基础价格范围-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      场地类型-->
      <el-form-item label="场地类型" prop="type">
        <!--        下拉框-->
        <el-select v-model="queryParams.type" placeholder="请选择场地类型" clearable size="small">
          <el-option label="篮球场" value="0"></el-option>
          <el-option label="羽毛球场" value="1"></el-option>
          <el-option label="乒乓球场" value="2"></el-option>
          <el-option label="游泳场" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="场地状态" prop="status">
        <!--        下拉框-->
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="可用" value="0"></el-option>
          <el-option label="正在使用" value="1"></el-option>
          <el-option label="正在维护" value="2"></el-option>
          <el-option label="关闭" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table v-loading="loading" :data="placeList">
      <!--    展示场馆类型    0 篮球 1羽毛 2乒乓 3游泳-->
      <el-table-column label="场馆类型" align="center" prop="type" width="120">
        <template v-slot="scope">
          <el-tag v-if="scope.row.type === 0">篮球场</el-tag>
          <el-tag v-else-if="scope.row.type === 1">羽毛球场</el-tag>
          <el-tag v-else-if="scope.row.type === 2">乒乓球场</el-tag>
          <el-tag v-else-if="scope.row.type === 3">游泳场</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="场地编号" align="center" prop="number" width="160"/>

      <!--      场地图片-->
      <el-table-column label="场地图片" align="center" prop="avatar" width="120">
        <template v-slot="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.image"/>
        </template>
      </el-table-column>

      <el-table-column label="场地当前状态" align="center" prop="status" width="110">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === 0">可用</el-tag>
          <el-tag v-else-if="scope.row.status === 1">正在使用</el-tag>
          <el-tag v-else-if="scope.row.status === 2">正在维护</el-tag>
          <el-tag v-else-if="scope.row.status === 3">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="基础价格(半小时)" align="center" prop="basePrice" width="150">
        <template v-slot="scope">
          <el-tag v-if="scope.row.basePrice">{{ scope.row.basePrice / 100 }}元</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="折扣" align="center" prop="strategyId" width="120">
        <template v-slot="scope">
          <!--      策略类型  策略id strategyId  循环策略表 strategyList 根据策略id找到策略名字 name-->
          <el-tag v-for="item in strategyList" v-if="item.id === scope.row.strategyId">{{ item.name }}</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="场地描述" align="center" prop="description"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="170">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOrder(scope.row)"
            v-hasPermi="['manager:member:edit']"
          >预约
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改场地管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <!--预约窗口  用户需要添加姓名 手机号 场地编号 预计使用人数
      开始时间（从当前时间开始 到折扣方案规定的可提前预约天数为止） 预约时长（步长半小时）动态判断该时间段有无其他人占用

      当开始时间和预约时长都选中后，向后台发送一个请求，判断该时间段是否有人占用 被占用就提示用户该时间段已经被占用 请重新选择
      否则 提示该时间段可以使用

      根据预约时长显示实际金额，实际金额=基础价格*半小时个数*该场地的折扣 动态显示 只读不可修改

      用户备注-->

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <!-- 场地信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场地类型">
              <el-input :value="currentPlace ? getPlaceTypeName(currentPlace.type) : ''" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场地编号">
              <el-input v-model="form.placeNumber" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="会员姓名" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入会员姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <!-- 预计使用人数 -->
        <el-form-item label="预计使用人数" prop="peopleCount">
          <el-input-number v-model="form.peopleCount" :min="1" :max="20" label="预计使用人数"></el-input-number>
        </el-form-item>

        <!-- 开始时间 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>

        <!-- 预约时长 -->
        <el-form-item label="预约时长" prop="duration">
          <el-select v-model="form.duration" placeholder="请选择预约时长">
            <el-option
              v-for="item in durationOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 实际金额 -->
        <el-form-item label="实际金额" prop="price">
<!--          只读  根据时长自动生成-->
          <el-tag v-model="form.price">{{ form.price / 100}}元</el-tag>
        </el-form-item>

        <!-- 用户备注 -->
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>

import {listPlace, getPlace, delPlace, addPlace, updatePlace} from "@/api/manager/place"
import {listStrategy} from "@/api/manager/strategy"
import {checkPlaceAvailability} from "@/api/manager/userReservation"
import {addReservationDTO} from "@/api/manager/userReservation";

export default {
  name: "userReservation",

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场地管理表格数据
      placeList: [],
      //策略管理数据
      strategyList: [],
      // 场馆类型选项
      placeTypeOptions: [
        {id: 0, name: '篮球场'},
        {id: 1, name: '羽毛球场'},
        {id: 2, name: '乒乓球场'},
        {id: 3, name: '游泳场'}
      ],

      timeAvailable: true, // 添加时间段是否可用的标志


      currentPlace: "", // 当前选中的场地

      // 时间选择器选项
      pickerOptions: {
        disabledDate(time) {
          // 禁用过去的日期
          return time.getTime() < Date.now() - 8.64e7;
        }
      },

      // 预约时长选项（半小时步长）
      durationOptions: [
        {value: 30, label: '0.5小时'},
        {value: 60, label: '1小时'},
        {value: 90, label: '1.5小时'},
        {value: 120, label: '2小时'},
        {value: 150, label: '2.5小时'},
        {value: 180, label: '3小时'},
        {value: 210, label: '3.5小时'},
        {value: 240, label: '4小时'}
      ],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        status: null
      },
      commonQueryParams: {
        pageNum: 1,
        pageSize: 10000
      },
      // 表单参数
      form: {},
      // 表单校验
      // 表单校验规则
      rules: {
        memberName: [
          {required: true, message: "会员姓名不能为空", trigger: "blur"}
        ],
        phone: [
          {required: true, message: "手机号不能为空", trigger: "blur"},
          {pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur"}
        ],
        peopleCount: [
          {required: true, message: "使用人数不能为空", trigger: "change"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "change"}
        ],
        duration: [
          {required: true, message: "预约时长不能为空", trigger: "change"}
        ]
      }
    }
  },

  created() {
    this.getList()
    this.getPolicyList()
  },


  // 监听
  watch: {
    // 监听开始时间和预约时长的变化
    'form.startTime': function (newVal, oldVal) {
      if (newVal && this.form.duration) {
        this.calculatePrice();
      }
    },
    'form.duration': function (newVal, oldVal) {
      if (newVal && this.form.startTime) {
        this.calculatePrice();
      }
    }
  },


  methods: {

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查时间段是否可用
          if (!this.timeAvailable) {
            this.$message.warning("请选择可用的时间段再提交！");
            return;
          }

          console.log("提交表单")
          // 构造提交数据
          const reservationData = {
            memberName: this.form.memberName, // 如果有会员姓名可以填入
            phone: this.form.phone,// 手机号
            courtId: this.currentPlace.id, // 场地ID
            startTime: this.form.startTime, // 开始时间
            duration: this.form.duration, // 预约时长(分钟)
            peopleCount: this.form.peopleCount, // 使用人数
            status: 0, // 状态 0未使用
            actualFee: Math.round(this.form.price), // 实际支付金额(分)
            notes: this.form.notes // 备注
          };

          // 调用API提交预约
          addReservationDTO(reservationData).then(response => {
            this.$message.success("预约提交成功！");
            this.open = false;
            this.reset();
            this.getList(); // 刷新列表
          }).catch(error => {
            this.$message.error("预约提交失败，请重试！");
            console.error(error);
          });
        }
      });
    },


    // 检查时间段是否被占用
    async checkTimeAvailability() {
      if (!this.currentPlace || !this.form.startTime || !this.form.duration) {
        this.timeAvailable = true;
        return;
      }

      try {
        const response = await checkPlaceAvailability({
          placeId: this.currentPlace.id,
          startTime: this.form.startTime,
          duration: this.form.duration
        });
        console.log(response);
        this.timeAvailable = response;

        if (response===false) {
          console.log("该时间段已被占用，请重新选择时间！")
          this.$message.warning("该时间段已被占用，请重新选择时间！");
        } else {
          console.log("该时间段可以使用！")
          this.$message.success("该时间段可以使用！");
        }
      } catch (error) {
        this.$message.error("检查时间段失败，请重试！");
        this.timeAvailable = false;
      }
    },

    // 计算实际金额
    calculatePrice() {
      if (!this.currentPlace || !this.form.startTime || !this.form.duration) {
        this.form.price = '';
        return;
      }

      // 获取场地的基础价格（单位：分）
      const basePrice = this.currentPlace.basePrice;

      // 计算半小时个数
      const halfHourCount = this.form.duration / 30;

      // 获取折扣策略
      const strategy = this.strategyList.find(item => item.id === this.currentPlace.strategyId);
      let discount = 1; // 默认无折扣

      if (strategy) {
        // 假设折扣以小数形式存储，如 0.8 表示 8 折
        discount = strategy.discount || 1;
      }

      // 计算实际金额（单位：分）
      const totalPrice = basePrice * halfHourCount * discount;

      // 转换为元并保留两位小数
      this.form.price = (totalPrice / 100).toFixed(2);

      // 检查时间段是否被占用
      this.checkTimeAvailability();
    },


    // 获取场地类型名称
    getPlaceTypeName(type) {
      const types = {
        0: '篮球场',
        1: '羽毛球场',
        2: '乒乓球场',
        3: '游泳场'
      };
      return types[type] || '未知场地';
    },
    /** 查询场地管理列表 */
    getList() {
      this.loading = true
      listPlace(this.queryParams).then(response => {
        this.placeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /*获取策略列表*/
    getPolicyList() {
      this.loading = true
      listStrategy(this.commonQueryParams).then(response => {
        this.strategyList = response.rows
        this.loading = false
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 表单重置
    reset() {
      this.form = {
        memberName: null,
        placeNumber: null,
        phone: null,
        peopleCount: null,
        price: null,
        notes: null,
        startTime: null,
        duration: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    /*预约按钮操作*/
    handleOrder(row) {
      this.reset();
      this.currentPlace = row;
      this.open = true;
      this.title = "场地预约";

      // 初始化表单数据
      this.form.placeNumber = row.number;


    }
  }
}
</script>
